#include "control.h"
#include "downloadmanager.h"
#include "mylib.h"
#include <QDebug>
#include <QCoreApplication>

DownloadManager *m_downloadManager;
MyLib *mylib;
Control *ctrl;

static bool libraryInit = false;

MyLib::MyLib()
{
    m_downloadManager = new DownloadManager;
    QObject::connect(m_downloadManager, &DownloadManager::sendSig, [=](){
        qDebug() << "+++receive sendSig";
    });
}

QString MyLib::hello()
{
    return "hello world";
}

void MyLib::startDownload()
{
    m_downloadManager->startDownload();
}

void MyLib::startDownload(std::function<int (int)> callback)
{
    callback(115);
}

void MyLib::sendSig()
{
    qDebug() << "MyLib::sendSig()";
    emit m_downloadManager->sendSig(123);
}

void initLibrary( )
{
    //获取QCoreApplication对象没有则创建一个
    QCoreApplication *qapp = QCoreApplication::instance();
    if (qapp == nullptr) {
        int argc = 0;
        char **argv = nullptr;
        qapp = new QCoreApplication(argc, argv);
    }
    //创建库所使用的事件循环对象
    QEventLoop eventloop;

    ctrl = new Control;
    m_downloadManager = new DownloadManager;

    QObject::connect(ctrl, &Control::startDownload, m_downloadManager, &DownloadManager::startDownload);
//    QObject::connect(m_downloadManager, &DownloadManager::sendSig, [=](){
//        qDebug() << "+++receive sendSig";
//    });

    //mylib.startDownload();
    //启动事件循环
    libraryInit = true;
    eventloop.exec();
}

void startDL()
{
    qDebug() << "startDL " << QThread::currentThreadId();
    emit ctrl->startDownload();

    //mylib->sendSig();
}
